import * as dayjs from 'dayjs';

export function GetUnixTime() {
  // @ts-ignore
  return Date.parse(new Date()) / 1000;
}

export function GetDateValue(fields: string[]): any {
  const date = GetUnixTime();
  const obj = {};
  fields.forEach((field) => {
    obj[field] = date;
  });
  return obj;
}

export function NumberToBool(value: unknown) {
  if (value === undefined || value == '') {
    return undefined;
  }
  if (typeof value == 'boolean') {
    return value;
  }
  if (value === 1) {
    return true;
  } else if (value === 0) {
    return false;
  }
}

export function GetClientIp(req: any) {
  return (
    req.headers['x-forwarded-for'] ||
    req.ip ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    ''
  );
}

export function Ipv6ToV4(ip: string) {
  if (ip.split(',').length > 0) {
    ip = ip.split(',')[0];
  }
  ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
  return ip;
}

export function GetUserAgent(req: any) {
  return req.headers['user-agent'];
}

export function GetLocalDate() {
  const date = new Date().valueOf();
  return new Date(date + 8 * 3600000);
}

export function GetLocalTime(
  date: string,
  format: string = 'YYYY-MM-DD HH:mm',
) {
  return dayjs(date).format(format);
}

export function getDayRange(date: string): [Date?, Date?] {
  if (!date) return [undefined, undefined];
  const d = dayjs(date);
  return [d.startOf('d').toDate(), d.endOf('d').toDate()];
}
